/**
 * Copyright 2009 by Christian Scheid. This file is part of the switch eclipse plugin and is licensed under the
 * GPL version 3. Please refer to the URL http://www.gnu.org/licenses/gpl-3.0.html for details.
 */
package org.digitalsoul.switchplugin;

import org.digitalsoul.switchplugin.patterns.CompoundPattern;

import org.digitalsoul.switchplugin.patterns.IPattern;


public class Finder {

    /**
     * @param currentFile
     * @param currentPattern
     * @param patterns
     * @return
     */
    public SwitchFile findNextFile(SwitchFile currentFile, PatternRing patterns) {
        SwitchFile matchingFile = null;
        IPattern currentPattern = findMatchingPattern(currentFile, patterns);
        if (currentPattern != null) {
            currentFile = currentPattern.undoFile(currentFile);
            patterns.spoolAfterPattern(currentPattern);
            for (IPattern pattern : patterns) {
                matchingFile = pattern.applyToFile(currentPattern, currentFile);
                if (matchingFile.exists()) {
                    break; 
                }
            }
        }
        return matchingFile;
    }

    /**
     * @param file
     * @param patterns
     * @return
     */
    protected IPattern findMatchingPattern(SwitchFile file, PatternRing patterns) {
        IPattern foundPattern = null;
        int numMatches = 0; 
        for (IPattern pattern : patterns) {
            if (pattern.matches(file)) {
                int matches = 1;
                if (pattern instanceof CompoundPattern) {
                    CompoundPattern cp = (CompoundPattern) pattern;
                    matches = cp.getMatches();
                }
                if (matches > numMatches) {
                    numMatches = matches;
                    foundPattern = pattern;
                }
            }
        }
        return foundPattern;
    }
}
